<?php
class liveInterfaceController extends base
{
    const liveDetailSchemeHead = 'joggers://liveDetail/';
    public function __construct($type='api')
    {
        parent::__construct($type);
    }

    /**
     * 1.查询微课列表接口
     * 分页，20条/页
     */
    public function dogetLiveList() {
        $uid = $this->uid;
        $page = common::request('page','G', 1 ,true);
        $offset = common::request('offset','G',20,true);
        $start = ($page - 1) * $offset;
        $list = $this->load('live/live')->getLiveList(array(
                                                        'start'=>$start,
                                                        'offset'=>$offset,
                                                        'uid'=>$uid
                                                    ));
        if (!$list) {
            $this->result['result'] = array('total'=>$this->load('live/live')->total, 'list'=>[]);
            exit;
        }
        $this->result['result'] = array('total'=>$this->load('live/live')->total, 'list'=>$list);
    }

    /**
     * 2.查询指定微课详情接口
     * （微课详情+聊天室ID+[商品ID+课程金额+是否已成功购买]+Ta的微课+推荐微课）
     */
    public function dogetLiveDetailById() {
        $uid = $this->uid;
        $liveId = common::request('liveId', 'G', 0, true);
        if (!$liveId){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $result = $this->load('live/live')->getLiveDetailById(array(
            'uid'=>$uid,
            'liveId'=>$liveId
        ));
        $this->result['result'] = $result;
    }

    /**
     * 查询聊天室内微课的相关信息
     */
    public function dogetLiveDetailForChatroom() {
        $uid = $this->uid;
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        $liveId = common::request('liveId', 'G', 0, true);
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $isJoin = $this->load('live/live')->getUserIsJoinLive($uid, $liveId);//查询是否参与了该微课
        if (!$isJoin) {
            $_ENV['error']->getErrors(8001);
            exit;
        }
        list($detail, $giftArr) = $this->load('live/live')->getLiveDetailForChatroom(array('liveId'=>$liveId));
        $this->result['result'] = array('detail'=>$detail, 'giftArr'=> $giftArr);
    }

    /**
     * 3.查询 指定微课消息列表接口
     * （基本信息+消息列表+礼物列表，筛选+分页，50条/页，排序规则：时间正序）
     */
    public function dogetLiveMsgAllList() {
        $uid = $this->uid;
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        $liveId = common::request('liveId', 'G', 0, true);
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $isJoin = $this->load('live/live')->getUserIsJoinLive($uid, $liveId);//查询是否参与了该微课
        if (!$isJoin) {
            $_ENV['error']->getErrors(8001);
            exit;
        }
        $type = common::request('type', 'G', 0, true);//0 全部消息 1 问答墙消息
        $mid = common::request('mid', 'G', 0, true);
        $offset = common::request('offset','G',20,true);
        $direc = common::request('direc','G','prev',true);
        $msgList = $this->load('live/live')->getLiveMsgAllList(array('uid'=>$uid,'liveId'=>$liveId, 'type'=>$type, 'mid'=>$mid, 'offset'=>$offset, 'direc'=>$direc));
        if (!$msgList) {
            $this->result['result'] = array('total'=>$this->load('live/live')->total,'msgList'=>$msgList);
            exit;
        }
       $this->result['result'] = array('total'=>$this->load('live/live')->total,'msgList'=>$msgList);
    }

    /**
     * 查询聊天室用户是否可以提问
     */
    public function dogetUserCanQues() {
        $uid = $this->uid;
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        $liveId = common::request('liveId', 'G', 0, true);
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $goldNum = (int)common::request('goldNum', 'G', 0, true);
        $status = $this->load('live/live')->getUserCanQues($uid, $liveId , $goldNum);
        if ($status < 0) {
            $errorMap = array('-1'=>101,'-2'=>8001, -3=>8002, -4=>103, -5=>8005, -6=>8008);//错误码映射
            $_ENV['error']->getErrors($errorMap[$status]);
            exit;
        }
        $this->result['result']['canQues'] = 1;
    }

    /**
     * 4.收集所有用户发送消息内容接口
     * （[包含主播、主持、普通用户]+回复问题的消息处理）
     */
    public function doaddUserMsg() {
        $uid = $this->uid;
        $liveId = common::request('liveId', 'P', 0, true);
        $replyImId = common::request('replyImId', 'P', '', true);
        $msgType = common::request('msgType', 'P', 0, true);//0 文字消息 1语音消息 2图片消息
        $imId =  common::request('imId', 'P', '', true);//融云消息ID
        $goldNum = (int)common::request('goldNum', 'P', 0, true);//提问需要扣除的元宝数
        //1 普通消息 先发融云 2 提问先发服务端 3 回应先发融云
        $type = common::request('icon', 'P', 0, true);// 0 普通消息 1 提问 2 回应消息
        $content = common::request('content', 'P', '', true); //消息内容
        $voiceSec = (int)common::request('voiceSec', 'P', '', true);//语音时长

        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        if (!in_array($type, array(0,1,2))) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        if (!trim($imId)) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        if($msgType == 1 && !$voiceSec) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $isExistImId2 = 0;
        if ($type == 2) {
            if (!$replyImId) {
                $_ENV['error']->getErrors(101);
                exit;
            } else {
                $isExistImId2 = $this->load('live/live')->getIsExistMsg($replyImId);
                if (!$isExistImId2) {
                    $_ENV['error']->getErrors(8004);
                    exit;
                }
            }
        }
        //查询消息是否存在
        $isExistImId = $this->load('live/live')->getIsExistMsg($imId);
        if ($isExistImId) {
            $_ENV['error']->getErrors(8004);
            exit;
        }
        //查询用户跟微课是否关联
        $isJoin = $this->load('live/live')->getUserIsJoinLive($uid, $liveId);
        if (!$isJoin) {
            $_ENV['error']->getErrors(8002);
            exit;
        }
        //是否被禁言
        $isGag = $this->load('live/live')->getUserIsGag($uid, $liveId);
        if ($isGag) {
            $_ENV['error']->getErrors(8008);
            exit;
        }
        $status  = $this->load('live/live')->addUserMsg(array(
             'uid'=>$uid,
            'liveId'=>$liveId,
            'type'=>$type,
            'replyMid'=>$isExistImId2,
            'msgType'=>$msgType,
            'imId'=>$imId,
            'content'=>$content,
            'goldNum'=>$goldNum,
            'voiceSec'=>$voiceSec
        ));
        if ($status < 0) {
            $errorMap = array('-1'=>101,'-2'=>8001, -3=>8002, -4=>103);//错误码映射
            $_ENV['error']->getErrors($errorMap[$status]);
            exit;
        }
        $this->result['result']['is_success'] = 0;
        if ($status) {
            $this->result['result']['is_success'] = 1;
        }
    }

    /**
     * 5.用户发布提问信息接口（元宝余额对应交互）--废除
     */
    public function dosendUserQues() {
        $uid = $this->uid;
        $liveId = common::request('liveId', 'P', 0, true);
        $content = common::request('content', 'P', 0, true);
        //todo
        $this->result['result']['is_success'] = 0;
        $result = 0;
        if ($result) {
            $this->result['result']['is_success'] = 1;
        }
    }

    /**
     * 6.查询主播或主持结束微课接口（结束+微课信息汇总）
     */
    public function dogetAnalysisForOverLive() {
        $liveId = common::request('liveId', 'G', 0, true);
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $result = $this->load('live/live')->getAnalysisForOverLive($liveId);
        $this->result['result'] = $result;
    }

    /**
     * 7.结束微课
     */
    public function dooverLive() {
        $uid = $this->uid;
        $liveId = common::request('liveId', 'P', 0, true);
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $status = $this->load('live/live')->overLive($liveId, $uid);
        if($status < 0) {
            $errorMap = array('-1'=>101,'-2'=>103);//错误码映射
            $_ENV['error']->getErrors($errorMap[$status]);
            exit;
        }
        $this->result['result']['is_success'] = 1;
    }

    /**
     * 8.查询指定微课所有用户提问及回答列表接口（排序规则：时间正序）--已合并 废除
     */
    public function dogetQuesWallByLiveId() {
    }

    /**
     * 查询指定聊天室已被禁言的用户列表接口
     */
    public function dogetGagUserList() {
        $liveId = common::request('liveId', 'G', 0, true);
        $id = common::request('id', 'G', 0, true);
        $offset = common::request('offset','G', 20, true);
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $result = [];
        $list = $this->load('live/live')->getGagUserList($liveId, $id, $offset);
        if (!$list) {
            $this->result['result'] = array('total'=>$this->load('live/live')->total,'list'=>$result);
            exit;
        }
       foreach ($list as $key=>$val) {
           $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'header');
           $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'nickname');
           $result[$key]['uid'] = $val['uid'];
           $result[$key]['header'] = $header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";
           $result[$key]['nickname'] = $nickname;
       }
        $this->result['result'] = array('total'=>$this->load('live/live')->total,'list'=>$result);
    }

    /**
     * 禁言指定聊天室的指定用户接口
     */
    public function doaddGagUser() {
        $uid = $this->uid;
        $liveId = common::request('liveId', 'P', 0, true);
        $gagUid = common::request('gagUid', 'P', 0, true);
        $minute = common::request('minute', 'P', 0, true);
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        if (!$gagUid) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        if (!$minute) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $result = $this->load('live/live')->addGagUser($liveId, $gagUid, $minute);
        $this->result['result']['is_success'] = 0;
        if ($result) {
            $this->result['result']['is_success'] = 1;
        }
    }

    /**
     * 解禁指定聊天室的指定用户接口
     */
public function dorollbackGagUser() {
        $uid = $this->uid;
        $liveId = common::request('liveId', 'P', 0, true);
        $gagUid = common::request('gagUid', 'P', 0, true);
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        if (!$gagUid) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $result = $this->load('live/live')->rollbackGagUser($liveId, $gagUid);
        $this->result['result']['is_success'] = 0;
        if ($result) {
            $this->result['result']['is_success'] = 1;
        }
    }

    /**
     * 用户打赏礼物接口（+广播）
     */
    public function dosendGift() {
        $uid = $this->uid;
        $liveId = common::request('liveId', 'P', 0, true);
        $giftId = common::request('giftId', 'P', 0, true);
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        if (!$giftId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $status = $this->load('live/live')->sendGift($uid, $liveId, $giftId);
        if ($status < 0) {
            $errorMap = array('-1'=>8001,'-2'=>101, -3=>8002);//错误码映射
            $_ENV['error']->getErrors($errorMap[$status]);
            exit;
        }
        $this->result['result']['is_success'] = 1;
    }

    /**
     * 用户喜欢问题接口（+广播）
     */
    public function doaddLight(){
        $uid = $this->uid;
        $liveId = common::request('liveId', 'P', 0, true);
        $imId = common::request('imId', 'P', 0, true);
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        if (!trim($imId)) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $status = $this->load('live/live')->addLight($uid, $liveId, $imId);
        if ($status < 0) {
            $errorMap = array('-1'=>8001,'-2'=>101,'-3'=>8003);//错误码映射
            $_ENV['error']->getErrors($errorMap[$status]);
            exit;
        }
        $this->result['result']['is_success'] = 1;
    }

    /**
     * 查询指定微课的用户打赏排行榜接口
     */
    public function dogetRankListByLiveId() {
        $uid =$this->uid;
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        $liveId = common::request('liveId', 'G', 0, true);
        $id = common::request('id', 'G', 0, true);//翻页ID
        $page = common::request('page','G', 1 ,true);
        $offset = common::request('offset','G',20,true);
        $start = ($page - 1) * $offset;
        $list = $this->load('live/live')->getRankListByLiveId(array(
            'liveId'=>$liveId,
            'start'=>$start,
            'offset'=>$offset
        ));
        $result = [];
        if ($list) {
           foreach ($list as $key=>$val) {
               $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'header');
               $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'nickname');
               $role = $this->load('live/live')->getUserRole($val['uid'], $liveId);
               $result[$key]['id'] = $val['id'];
               $result[$key]['rankNum'] = $key+1;
               $result[$key]['userInfo'] = array(
                   'uid'=>$val['uid'],
                   'header'=>$header,
                   'nickname'=>$nickname,
                   'role'=>$role,
                   'goldNum'=>$val['totalGoldNum']
               );
           }
        }
        $this->result['result'] = array('total'=>$this->load('live/live')->total, 'list'=>$result);
    }

    /**
     * 用户加入聊天室
     */
    public function doaddUserToChatroom() {
        $uid = $this->uid;
        $liveId = common::request('liveId', 'P', 0, true);
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $status =  $this->load('live/live')->addUserToChatroom($uid, $liveId);
        if ($status < 0) {
            $errorMap = array('-1'=>101, '-2'=>8001, '-3'=>8006, '-4'=>8007);//错误码映射
            $_ENV['error']->getErrors($errorMap[$status]);
            exit;
        }
        $this->result['result']['is_success'] = 1;
    }

    /**
     * 更新语音消息已读
     */
    public function doaddVoiceRead() {
        $uid = $this->uid;
        $imId =  common::request('imId', 'P', '', true);//融云消息ID
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        if (!$imId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        //消息是否存在
        $isExistImId = $this->load('live/live')->getIsExistMsg($imId);
        if (!$isExistImId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        //查看融云消息的微课ID
        $liveId = $this->load('live/live')->getLiveIdByImid($imId);
        if (!$liveId) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        //查询用户是否参与了微课
        $isJoin = $this->load('live/live')->getUserIsJoinLive($uid, $liveId);
        if (!$isJoin) {
            $_ENV['error']->getErrors(8001);
            exit;
        }
        $result =  $this->load('live/live')->addVoiceRead($uid, $imId);
        $this->result['result']['is_success'] = 0;
        if ($result) {
            $this->result['result']['is_success'] = 1;
        }
    }
    /***********************************元宝START*************************************/

    /**
     *查询元宝充值商品列表接口（+元宝配置）
     */
    public function dogetGoldConfig() {
        $uid = $this->uid;
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'header');
        $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'nickname');
        $userGoldNum = $this->db->getOne("select gold_num from r_user_ext where uid=$uid");
        $goldConfiguration = common::$goldConfiguration;
        $result = array(
                    'userInfo'=>array(
                        'uid'=>$uid,
                        'nickname'=>$nickname,
                        'header'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png",
                        'goldNum'=>$userGoldNum
                    ),
                    'goldConfig'=>$goldConfiguration
                );
        $this->result['result'] = $result;
    }

    /**
     * 查询用户元宝充值消费记录接口（我的账单）
     */
    public function dogetUserGoldCostList() {
        $uid = $this->uid;
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        $id = common::request('id', 'G', 0, true);
        $offset = common::request('offset', 'G', 20, true);
        $list = $this->load('live/live')->getUserGoldCostList(array('uid'=>$uid, 'id'=>$id, 'offset'=>$offset));
        $result = [];
        if ($list) {
            foreach($list as $key=>$val) {
                $title = '';
                $shortDetail = '';
                switch($val['type']) {
                    case 1:
                        $liveInfo = $this->load('live/live')->getLiveInfo($val['live_id'], 'title');
                        $title  = $liveInfo ? $liveInfo['title'] : '';
                        $shortDetail = $val['balance_type']==1 ? '向您提问问题' : '提问问题';
                        break;
                    case 2:
                        $liveInfo = $this->load('live/live')->getLiveInfo($val['live_id'], 'title');
                        $title  = $liveInfo ? $liveInfo['title'] : '';
                        $shortDetail = $val['balance_type']==1 ? '对您打赏礼物' : '打赏礼物';
                        break;
                    case 3:
                        $title = '充值';
                        $shortDetail = '充值'.$val['gold_price'].' 元，获得'.$val['gold_num']+$val['give_gold_num'].'小元宝';
                        break;
                    default:
                        break;
                }
                $result[$key]['id'] = $val['id'];
                $result[$key]['title'] = $title;//微课名称|充值
                $result[$key]['shortDetail'] = $shortDetail;
                $result[$key]['balanceType'] = $val['balance_type'];//1：收入| 0：支出
                $result[$key]['goldNum'] = $val['gold_num']+$val['give_gold_num'];
                $result[$key]['formartTime'] = $val['create_time'] ? date('Y.m.d') : '';//'2017.1.6'
            }
        }
        $this->result['result'] = array('total'=>$this->load('live/live')->total, 'list'=>$result);
    }
    /***********************************元宝END**************************************/

    /**********************************消息START*************************************/
    /**
     * 消息列表
     */
    public function dogetMsgList() {
        $uid = $this->uid;
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        $mid = common::request('mid','G', 0 ,true);
        $offset = common::request('offset','G',20,true);
        $list = $this->load('live/messageLive')->getMsgList(array(
            'uid'=>$uid,
            'mid'=>$mid,
            'offset'=>$offset
        ));
        $result = [];
        if ($list) {
            foreach ($list as $key => $val) {
                $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['to_uid'], 'nickname');
                $liveInfo = $this->load('live/live')->getLiveInfo($val['live_id'], 'id,title,image_url');
                $title = $liveInfo ? $liveInfo['title'] : '';
                $msgTitle = '';
                $voiceSec = 0;
                $msgType = 0;
                $content = '';
                $quesContent = '';
                if ($val['desc_type'] == 'L1') {
                    $msgTitle = $nickname . '，您好，您参与的微课即将开始-' . $title;
                } elseif ($val['desc_type'] == 'L2') {
                    $msgTitle = $nickname . '，您好，您参与的' . $title;
                    //提问信息
                    $arrChatroomMsg = $this->db->getRow("select parent_id,role from r_live_chatroom_message where id={$val['mid']}");
                    $arrChatroomMsgExt = $this->db->getRow("select content,voice_sec,msg_type from r_live_chatroom_message_ext where mid={$val['mid']}");
                    //回复信息
                    if ($arrChatroomMsg) {
                        $arrChatroomMsgExt2 = $this->db->getRow("select content,voice_sec,msg_type from r_live_chatroom_message_ext where mid={$arrChatroomMsg['parent_id']}");
                        $quesContent = $arrChatroomMsgExt2 ? '提问的问题：'.$arrChatroomMsgExt2['content'] : '';
                    }
                    if ($arrChatroomMsgExt) {
                        $msgType = $arrChatroomMsgExt['msg_type'];
                        $content = '主讲答复：'.$arrChatroomMsgExt['content'];
                        $voiceSec = $arrChatroomMsgExt['voice_sec'];
                    }
                }
                $result[$key]['liveIcon'] = $liveInfo['image_url'] ? $liveInfo['image_url'] :$this->config['host'] . '/static/images/share/pao.png';
                $result[$key]['msgInfo'] = array(
                    'id' => $val['id'],
                    'url' => self::liveDetailSchemeHead . $val['live_id'],
                    'descType' => $val['desc_type'],
                    'title' => $msgTitle,
                    'msgType' => $msgType,
                    'quesContent' => $quesContent,
                    'content' => $content,
                    'voiceSec' => $voiceSec
                );

            }
            sort($result);
        }
        $this->result['result'] = array('total'=>$this->load('live/messageLive')->total, 'list'=>$result);
    }
    /**********************************消息END*************************************/
}
